package com.xinsoft.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.InOrOutStock;
import com.xinsoft.entity.po.*;
import com.xinsoft.service.*;
import com.xinsoft.mapper.ScmMoveOutstockMapper;
import com.xinsoft.utils.TokenUtil;
import lombok.Synchronized;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 13370
 * @description 针对表【scm_move_outstock(调拨出库)】的数据库操作Service实现
 * @createDate 2023-08-17 09:51:59
 */
@Service
public class ScmMoveOutstockServiceImpl extends ServiceImpl<ScmMoveOutstockMapper, ScmMoveOutstock>
        implements ScmMoveOutstockService {


    @Autowired
    private ScmStockService stockService;
    @Autowired
    private SysDocumentNumService sysDocumentNumService;
    @Autowired
    private ScmMoveOutstockItemService moveOutstockItemService;

    @Override
    public void audit(Integer id) {
        ScmMoveOutstock outstock = this.getById(id);
        if (Const.AUDIT_STATUS_NORMAL.equals(outstock.getAuditStatus())) {
            throw new BDException("该单据已审核，无需重复审核");
        }
        outstock.setAuditId(TokenUtil.getUserId());
        outstock.setAuditTime(new Date());
        outstock.setAuditStatus(Const.AUDIT_STATUS_NORMAL);
        this.updateById(outstock);

        // 更新库存
        List<InOrOutStock> inOrOutStockList = this.getInOrOutStockList(id);
        stockService.updateInventory(Const.SourceBillType.YKYC, outstock.getOutstockCode(), inOrOutStockList, Const.ChangeType.SUBTRACT);
    }

    /**
     * 获取出入库明细列表
     * @param id
     * @return {@link List}<{@link InOrOutStock}>
     */
    public List<InOrOutStock> getInOrOutStockList(Integer id) {
        List<InOrOutStock> list = new ArrayList<>();
        List<ScmMoveOutstockItem> items = moveOutstockItemService.list(Wrappers.lambdaQuery(ScmMoveOutstockItem.class).eq(ScmMoveOutstockItem::getOutstockId, id));
        items.forEach(item -> {
            InOrOutStock inOrOutStock = new InOrOutStock();
            BeanUtils.copyProperties(item,inOrOutStock);
            inOrOutStock.setQty(item.getOutstockNum());
            list.add(inOrOutStock);
        });
        return list;
    }

}




